////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                                                                            //
//                                                         WNProject                                                          //
//                                                                                                                            //
//            This file is distributed under the BSD 2-Clause open source license. See License.txt for details.               //
//                                                                                                                            //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//#pragma once

#ifndef __WN_CONCURRENCY_SEMAPHORE_H__
#define __WN_CONCURRENCY_SEMAPHORE_H__

#include "WNCore/inc/WNPlatform.h"
#include "WNCore/inc/WNTypes.h"
#include "WNCore/inc/WNMacros.h"

#ifdef _WN_WINDOWS
    #include <windows.h>
#elif defined _WN_LINUX
    #include <semaphore.h>
#endif



namespace WNConcurrency {
    class WNSemaphore {
    public:
        WN_INLINE WNSemaphore(WN_UINT32 _count = 0);
        WN_INLINE ~WNSemaphore();

        WN_INLINE WN_VOID Lock();
        WN_INLINE WN_BOOL TryLock();
        WN_INLINE WN_VOID Unlock();

        WN_INLINE WN_INT32 GetCount() const;

    private:
        #ifdef _WN_WINDOWS
            HANDLE mHandle;
        #elif defined _WN_LINUX
            sem_t mSemaphore;
        #endif
    };

    class WNSemaphoreScopeLock {
    public:
        WN_INLINE WNSemaphoreScopeLock(WNSemaphore& _semaphore);
        WN_INLINE ~WNSemaphoreScopeLock();

    private:
        WNSemaphore& mSemaphore;

        WN_BOOL mLocked;
    };
}

#define WN_SEMAPHORE_SCOPE_LOCK(_semaphore) WNSemaphoreScopeLock WN_UNIQUE_VARIABLE(semaphore)(_semaphore)

#include "WNConcurrency/inc/WNSemaphore.inl"

#endif // __WN_CONCURRENCY_SEMAPHORE_H__
